package com.nova.android.tvlauncher.ui.adapter.atv

import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.cardview.widget.CardView
import androidx.core.view.isVisible
import androidx.fragment.app.FragmentActivity
import androidx.leanback.widget.BaseGridView
import androidx.leanback.widget.VerticalGridView
import androidx.lifecycle.lifecycleScope
import com.nova.android.tvlauncher.R
import com.nova.android.tvlauncher.bean.atv_bean.HomeParentDto
import com.nova.android.tvlauncher.bean.atv_bean.HomeProgramDto
import com.nova.android.tvlauncher.databinding.ItemAppChildAtv2Binding
import com.nova.android.tvlauncher.databinding.ItemAppParentAtvBinding
import com.nova.android.tvlauncher.ext.fadeView
import com.nova.android.tvlauncher.ext.loadWithBackground
import com.nova.android.tvlauncher.ext.toggle16to9Scale
import com.nova.android.tvlauncher.ui.view.ad.AdManagerImpl
import com.nova.android.tvlauncher.ui.view.atv.HomeLeftMenuAtvView
import com_github_lib_base.currentActivity
import com_github_lib_base.ext.clickNoRepeat
import com_github_lib_base.ext.dimenValue
import com_github_lib_base.ext.height
import com_github_lib_base.ext.openApp
import com_github_lib_base.ext.rv.BindAdapter
import com_github_lib_base.ext.rv.setup
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import java.net.URISyntaxException
import kotlin.coroutines.resume

object HomeListChannelDataAtvAdapter {

    var adJob: Job? = null

    fun bindData(
        itemParentBinding: ItemAppParentAtvBinding,
        bindingContext: BindAdapter,
        rvHome: VerticalGridView,

        ) {
        val item = bindingContext.getModel<HomeParentDto>()
        val items = bindingContext.models
        val parentPosition = bindingContext.modelPosition

        itemParentBinding.rvHorizontal.setWindowAlignment(BaseGridView.WINDOW_ALIGN_BOTH_EDGE);
        itemParentBinding.rvHorizontal.setWindowAlignmentOffset(com.codeZeng.lib_dimen.R.dimen.qb_px_23.dimenValue());
        itemParentBinding.rvHorizontal.setWindowAlignmentOffsetPercent(0f);
        itemParentBinding.rvHorizontal.setItemAlignmentOffsetPercent(0f);
        itemParentBinding.rvHorizontal.setup(item.recommondInfoDtoList!!) {
            addType(HomeProgramDto::class, R.layout.item_app_child_atv_2)
            onBind {
                val itemBinding = getBinding<ItemAppChildAtv2Binding>()
                val item = getModel<HomeProgramDto>()
                itemBinding.ivBigicon.loadWithBackground(item.programCover.toString())
                //Glide.with(appContext).load(item.programCover).into(itemBinding.ivBigicon)
                itemParentBinding.tvDetailTitle.text = item.programTitle
                itemParentBinding.tvDetailSubtitle.text = item.programDesc

                itemBinding.ivBigicon.isVisible = true
                if (item.isAd) {

                    adJob?.cancel() // 取消之前的任务
                    adJob = (currentActivity as FragmentActivity).lifecycleScope.launch {
                        while (isActive) {
                            delay(5000) // 初始或完成后的 10 秒间隔
                            suspendCancellableCoroutine<Unit> { continuation ->

                                AdManagerImpl.showAd(
                                    itemBinding.flAd,
                                    adStart = {
                                        itemBinding.flAd.isVisible = true
                                        itemBinding.ivBigicon.isVisible = false
                                    },
                                    adError = {
                                        itemBinding.flAd.isVisible = false
                                        itemBinding.ivBigicon.isVisible = true
                                        continuation.resume(Unit)
                                    },
                                    adComplete = {
                                        itemBinding.flAd.isVisible = false
                                        itemBinding.ivBigicon.isVisible = true
                                        continuation.resume(Unit)
                                    }
                                )
                            }
                        }
                    }
                } else {
                    itemBinding.flAd.isVisible = false
                    itemBinding.ivBigicon.isVisible = true
                }




                itemBinding.rlIcon.onKeyEvent(
                    modelPosition,
                    items,
                    parentPosition,
                    rvHome,
                    itemParentBinding,
                    item
                )
                itemParentBinding.leftMenu.tvMove().clickNoRepeat {
                    itemParentBinding.root.isFocusable = true
                    itemParentBinding.root.isFocusableInTouchMode = true
                    itemParentBinding.leftMenu.tvRemove().visibility = View.INVISIBLE
                    itemParentBinding.root.setPadding(0, 20, 20, 20)
                    itemParentBinding.root.requestFocus()
                }

                itemParentBinding.leftMenu.tvMove().setOnKeyListener { v, keyCode, event ->
                    if (event.action == KeyEvent.ACTION_DOWN) {
                        when (keyCode) {
                            KeyEvent.KEYCODE_DPAD_RIGHT, KeyEvent.KEYCODE_BACK -> {
                                items.forEachIndexed { index, dto ->
                                    if (dto is HomeParentDto) {
                                        dto.isLeftMenuShowed = false
                                        dto.isShowLestArrow = false
                                        if (index != parentPosition) {

                                            rvHome.post { rvHome.adapter?.notifyItemChanged(index) }


                                        } else {
                                            dto.isShowLestArrow = true
                                            itemParentBinding.leftMenu.tvMove().isVisible = false
                                            itemParentBinding.leftMenu.tvRemove().isVisible = false
                                            itemParentBinding.leftMenu.leftArrow().isVisible = true
                                            //itemParentBinding.rvHorizontal.requestFocus()
                                        }
                                    }

                                }
                                true
                            }

                            KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_CENTER -> false
                            else -> true
                        }


                    } else false
                }


            }
        }

        //itemParentBinding.rvHorizontal.itemAnimator = null
    }

    private var itemFocusJob: Job? = null
    private val POSITION_DELAY = 100L // 延迟 100ms 确保最后状态

    // 用于跟踪上一次的 parentPosition
    var lastParentPosition: Int? = null
    var isCanRemove: Boolean = true

    private fun CardView.onKeyEvent(
        modelPosition: Int,
        items: List<Any>,
        parentPosition: Int,
        rvHome: VerticalGridView,
        itemParentBinding: ItemAppParentAtvBinding,
        item: HomeProgramDto
    ) {
        this.clickNoRepeat {
            if (item.programId == null) {
                var packageName = (items[parentPosition] as HomeParentDto).packageName
                /*if(packageName=="com.netflix.mediaclient"){
                    val isInstalled = try {
                        appContext.packageManager.getPackageInfo(packageName, 0)
                        true
                    } catch (_: Exception) {
                        false
                    }
                    if(!isInstalled){
                        packageName = "com.netflix.ninja"
                    }
                }*/
                if (packageName.isNotEmpty()) packageName.openApp(item.intentUrl)
            } else {
                currentActivity?.let { enterVideo(it, item.intentUrl.toString()) }
            }
        }
        this.setOnKeyListener { v, keyCode, event ->
            (event.action == KeyEvent.ACTION_DOWN &&
                    keyCode == KeyEvent.KEYCODE_DPAD_LEFT &&
                    modelPosition == 0).also { isHandled ->
                if (isHandled) {
                    if ((items[parentPosition] as HomeParentDto).channelId <= 0) isCanRemove =
                        false else isCanRemove = true
                    items.forEachIndexed { index, dto ->
                        if (dto is HomeParentDto) {
                            dto.isLeftMenuShowed = true
                            if (index != parentPosition) {
                                rvHome.post { rvHome.adapter?.notifyItemChanged(index) }


                            } else {
                                if (!isCanRemove) {
                                    itemParentBinding.leftMenu.tvRemove().visibility = View.GONE
                                } else {
                                    itemParentBinding.leftMenu.tvRemove().isVisible = true
                                }

                                itemParentBinding.leftMenu.tvMove().isVisible = true
                                itemParentBinding.leftMenu.leftArrow().isVisible = false
                                itemParentBinding.leftMenu.tvMove().requestFocus()
                            }
                        }

                    }

                    //rvHome.requestLayout()
                }
            }


        }
        this.setOnFocusChangeListener { v, hasFocus ->
            // 判断是否需要延迟
            /* val needDelay = lastParentPosition != null && lastParentPosition != parentPosition

             // 更新 lastParentPosition
             lastParentPosition = parentPosition
             itemFocusJob?.cancel() // 取消旧的延迟任务
             itemFocusJob = (currentActivity as FragmentActivity).lifecycleScope.launch {
                 if (needDelay) {
                     delay(POSITION_DELAY) // 仅在 parentPosition 变化时延迟
                 }

             }*/

            if (hasFocus) {
                items.forEachIndexed { index, dto ->
                    if (dto is HomeParentDto) {
                        if (index != parentPosition) {
                            dto.isShowLestArrow = false

                            val childView = rvHome.getChildAt(index)

                            val leftMenu =
                                childView?.findViewById<HomeLeftMenuAtvView>(R.id.left_menu)

                            leftMenu?.leftArrow()?.visibility = View.INVISIBLE


                        } else {
                            curPosition = parentPosition
                            dto.isShowLestArrow = true
                            //itemParentBinding.leftMenu.leftArrow().isVisible = true
                            if (modelPosition == 0) {
                                itemParentBinding.leftMenu.leftArrow().isVisible = true
                            } else {
                                itemParentBinding.leftMenu.leftArrow().visibility = View.INVISIBLE
                            }
                        }
                    }

                }
            } else {
                if (parentPosition == 2) {
                    rvHome.postDelayed({
                        if (curPosition <= 2) {
                            val childView = rvHome.getChildAt(2)

                            val leftMenu =
                                childView?.findViewById<HomeLeftMenuAtvView>(R.id.left_menu)


                            if (items[parentPosition] is HomeParentDto) {
                                if ((items[parentPosition] as HomeParentDto).isLeftMenuShowed) {
                                    leftMenu?.leftArrow()?.visibility = View.GONE
                                } else {
                                    leftMenu?.leftArrow()?.visibility = View.INVISIBLE
                                }
                            }

                        }

                    }, 100)

                }
            }

            this@onKeyEvent.toggle16to9Scale(modelPosition == 0, hasFocus)
            if (hasFocus) {
                itemParentBinding.tvTitle.height(com.codeZeng.lib_dimen.R.dimen.qb_px_30.dimenValue())
                itemParentBinding.tvDetailSubtitle.height(com.codeZeng.lib_dimen.R.dimen.qb_px_30.dimenValue())
                itemParentBinding.tvDetailTitle.height(com.codeZeng.lib_dimen.R.dimen.qb_px_30.dimenValue())
                //itemParentBinding.rvHorizontal.height(((com.codeZeng.lib_dimen.R.dimen.qb_px_90.dimenValue()) * 1.25).toInt())
                itemParentBinding.tvDetailTitle.fadeView(true)
                itemParentBinding.tvDetailSubtitle.fadeView(true)
            } else {
                itemParentBinding.tvTitle.height(ViewGroup.LayoutParams.WRAP_CONTENT)
                itemParentBinding.tvDetailSubtitle.height(ViewGroup.LayoutParams.WRAP_CONTENT)
                itemParentBinding.tvDetailTitle.height(ViewGroup.LayoutParams.WRAP_CONTENT)
                //itemParentBinding.rvHorizontal.height(((com.codeZeng.lib_dimen.R.dimen.qb_px_90.dimenValue())).toInt())

                itemParentBinding.tvDetailTitle.isVisible = false
                itemParentBinding.tvDetailSubtitle.isVisible = false
            }


        }
    }

    var curPosition = 0

    fun enterVideo(context: Context, intentUri: String) {

        try {
            val intent = Intent.parseUri(intentUri, 0)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            context.startActivity(intent)
        } catch (e: URISyntaxException) {
            e.printStackTrace()
        } catch (e: ActivityNotFoundException) {
            e.printStackTrace()
            Toast.makeText(context, "未找到目标应用", Toast.LENGTH_SHORT).show()
        }

    }


}